<template>
  <div class="login">
    <van-nav-bar title="标题" />

    <van-cell-group>
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :error-message="mobile_errmsg"
      />
      <van-field
        v-model="code"
        required
        label="短信验证码"
        placeholder="请输入短信验证码"
        :error-message="code_errmsg"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div class="btn-wrap">
      <van-button type="info" @click="login"> 登录 </van-button>
      <!-- <van-button @click="getUserInfo">获取个人信息</van-button> -->
    </div>
  </div>
</template>

<script>
import { reqLogin } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      mobile: '13579888888',
      code: '246810',
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },
  methods: {
    ...mapMutations(['setTokenInfo']),
    // 进行校验  校验规则
    validate () {
      if (this.mobile.trim() === '') {
        this.mobile_errmsg = '手机号码不能为空'
        return false
      }
      if (!/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(this.mobile)) {
        this.mobile_errmsg = '请输入正确手机号码'
        return false
      }
      this.mobile_errmsg = ''
      if (this.code.trim() === '') {
        this.code_errmsg = '验证码不能为空'
        return false
      }
      if (!(/^\d{6}$/.test(this.code))) {
        this.code_errmsg = '请输入正确验证码'
        return false
      }
      this.code_errmsg = ''
      return true
    },

    async login () {
      // 登录前校验
      if (!this.validate()) return

      this.$toast.loading({
        message: '拼命加载中...',
        forbidClick: true, // 禁止背景点击
        overlay: true, // 背景遮罩层
        duration: 0 // 展示时长
      })
      try {
        const res = await reqLogin(
          this.mobile,
          this.code
        )
        console.log(res.data)
        this.$toast.success('登录成功')
        // 跳转到首页(layout)
        // 尝试获取地址栏的参数
        this.setTokenInfo(res.data.data)
        const backto = this.$route.query.backto
        this.$router.push(backto || '/')
        // this.$router.push()
      } catch (err) {
        console.log(err)
        this.$toast.fail('加载失败')
      }
    }
    // async getUserInfo () {
    //   try {
    //     const res = await reqGetProfile()
    //     console.log(res.data.data)
    //   } catch (err) {
    //     console.log(err)
    //   }
    // }
  }
}
</script>

<style lang='scss' scoped>
.login {
  .btn-wrap {
    padding: 20px;
    .van-button {
      width: 100%;
      background-color: #3196fa;
      color: #fff;
      border-radius: 50px;
    }
  }
}
</style>
